<?php

class WebSocket
{
    private $server;

    public function __construct()
    {

        $server = new \Swoole\WebSocket\Server("0.0.0.0", 9503);
        $this->server = $server;

        $this->open();
        $this->message();
        $this->request();
        $this->close();

        $this->server->start();

    }

    public function open()
    {
        $this->server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
            //echo "server: handshake success with fd {$request->fd}" , PHP_EOL;
        });
    }

    public function message()
    {
        $this->server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data}" , PHP_EOL;

            $content = trim(fgets(STDIN));
            $this->server->push($frame->fd, $content);
        });
    }

    public function request()
    {
        $server = $this->server;
        $this->server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){

            $fd = $request->post['fd'];
            $content = $request->post['content'];

            if ($fd == 0) {
                foreach ($server->connections as $fd) {
                    if ($server->isEstablished($fd)) {
                        $server->push($fd, $content);
                    }
                }
            } else {
                if ($server->isEstablished($fd)) {
                    $server->push($fd, $content);
                }
            }
        });
    }

    public function close()
    {
        $this->server->on('close', function ($server, $fd) {
            echo "client {$fd} closed", PHP_EOL;
        });
    }
}


new WebSocket();